package meterMonitor.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import meterMonitor.mapper.DataRecMapper;
import meterMonitor.mapper.DeviceInfoMapper;
import meterMonitor.mapper.LineMapper;
import meterMonitor.mapper.LotnumRecMapper;
import meterMonitor.model.DataRecPO;
import meterMonitor.model.DeviceInfoPO;
import meterMonitor.model.LinePO;
import meterMonitor.model.bo.LotnumRecBO;
import meterMonitor.model.vo.CallParameter;
import meterMonitor.model.vo.DataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DataRecService {
    @Autowired
    private DataRecMapper dataRecMapper;
    @Autowired
    private DeviceInfoMapper deviceInfoMapper;
    @Autowired
    private LineMapper lineMapper;
    @Autowired
    private LotnumRecMapper lotnumRecMapper;

    public void updateDataRec(DataRecPO dataRec) {
        dataRecMapper.updateDataRec(dataRec);
    }

    @Deprecated
    public List<LotnumRecBO> queryDataRecFromPartitionTable(LotnumRecBO param) {
        String tableName = concatTableName(param.getLineId());
        // 根据查询条件查询工单信息
        List<LotnumRecBO> lotnums = lotnumRecMapper.querylotnum(param);
        int dealType = param.getLotState();
        for (LotnumRecBO lotRec : lotnums) {
            // 遍历查询需要的温度、压力、流量、浓度等数据
            DataRecPO temp = dataRecMapper.queryDataRecFromPartitionTable(tableName, lotRec.getLotId(), 1, dealType); // 温度
            DataRecPO press = dataRecMapper.queryDataRecFromPartitionTable(tableName, lotRec.getLotId(), 2, dealType); // 压力
            DataRecPO flow = dataRecMapper.queryDataRecFromPartitionTable(tableName, lotRec.getLotId(), 3, dealType); // 流量
            DataRecPO concn1 = dataRecMapper.queryDataRecFromPartitionTable(tableName, lotRec.getLotId(), 7, dealType); // 硫酸浓度，未知
            DataRecPO concn2 = dataRecMapper.queryDataRecFromPartitionTable(tableName, lotRec.getLotId(), 8, dealType); // 碳酸钠浓度，未知
            DataRecPO concn3 = dataRecMapper.queryDataRecFromPartitionTable(tableName, lotRec.getLotId(), 9, dealType); // 氢氧化钠浓度，未知
            if (Objects.nonNull(temp)) {
                lotRec.setTemp(temp.getDataValue());
            }
            if (Objects.nonNull(press)) {
                lotRec.setPress(press.getDataValue());
            }
            if (Objects.nonNull(flow)) {
                lotRec.setFlow(flow.getDataValue());
            }
            if (Objects.nonNull(concn1)) {
                lotRec.setConcnH2SO4(concn1.getDataValue());
            }
            if (Objects.nonNull(concn2)) {
                lotRec.setConcnNACO3(concn2.getDataValue());
            }
            if (Objects.nonNull(concn3)) {
                lotRec.setConcnNaOH(concn3.getDataValue());
            }
        }
        return lotnums;
    }

    public List<DataRecPO> queryHistory(CallParameter param) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String lineIds = param.getLineIds();
        String[] split = lineIds.split(",");
        List<DataRecPO> list = new ArrayList<>();
        List<String> tableNames = null;
        for (int i = 0; i < split.length; i++) {
            tableNames = concatTableName(Integer.valueOf(split[i]), param.getStartTime(), param.getEndTime());
            for (String tableName : tableNames) {
                List<DataRecPO> dataRecs = dataRecMapper.queryHistory(tableName, param.getSlotIds(), param.getDevTypes(), param.getStartTime(), param.getEndTime(), param.getDevIds());
                list.addAll(dataRecs);
            }
        }
        return list;
    }

    public void download(String fileName, String sheetName, CallParameter callParameter) {
        List<DataRecPO> datas = dataRecMapper.queryDataRec(callParameter);
        EasyExcel.write(fileName, DataRecPO.class).sheet(sheetName).doWrite(datas);
    }


    public JSONObject liquidMedicine() {
        // 设备类型  8.碳酸钠 9.氢氧化钠 11.氯酸钠12盐酸
        JSONObject result = new JSONObject();

        Map<String, List<DataVO>> datas1 = new HashMap<>();
        Map<String, List<DataVO>> datas2 = new HashMap<>();
        Map<String, List<DataVO>> datas3 = new HashMap<>();
        Map<String, List<DataVO>> datas4 = new HashMap<>();
        Map<String, List<DataVO>> datas5 = new HashMap<>();


        Map<Integer, String> lineRel = new HashMap<>();
        // 查询产线
        List<LinePO> lines = lineMapper.queryLine(new LinePO());

        List<Timestamp> dateList1 = new ArrayList<>();
        List<Timestamp> dateList2 = new ArrayList<>();
        List<Timestamp> dateList3 = new ArrayList<>();
        List<Timestamp> dateList4 = new ArrayList<>();
        List<Timestamp> dateList5 = new ArrayList<>();


        // 构建表名
        String tableName = null;
        for (LinePO line : lines) {
            tableName = concatTableName(line.getId());
            dateList1.addAll(dataRecMapper.getRecTimes(tableName, 8));
            dateList2.addAll(dataRecMapper.getRecTimes(tableName, 9));
            dateList3.addAll(dataRecMapper.getRecTimes(tableName, 11));
            dateList4.addAll(dataRecMapper.getRecTimes(tableName, 12));
            dateList5.addAll(dataRecMapper.getRecTimes(tableName, 10));
            lineRel.put(line.getId(), line.getName());
        }

        // Collections.sort(dateList1);
        // Collections.sort(dateList2);
        // Collections.sort(dateList3);
        // Collections.sort(dateList4);
        // Collections.sort(dateList5);


        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        List<String> dateList11 = new ArrayList<>();
        List<String> dateList21 = new ArrayList<>();
        List<String> dateList31 = new ArrayList<>();
        List<String> dateList41 = new ArrayList<>();
        List<String> dateList51 = new ArrayList<>();


        // 对日期进行转换
        for (Timestamp t : dateList1) {
            String format = df.format(new Date(t.getTime()));
            if (!dateList11.contains(format)) {
                dateList11.add(format);
            }
        }
        for (Timestamp t : dateList2) {
            String format = df.format(new Date(t.getTime()));
            if (!dateList21.contains(format)) {
                dateList21.add(format);
            }
        }
        for (Timestamp t : dateList3) {
            String format = df.format(new Date(t.getTime()));
            if (!dateList31.contains(format)) {
                dateList31.add(format);
            }
        }

        for (Timestamp t : dateList4) {
            String format = df.format(new Date(t.getTime()));
            if (!dateList41.contains(format)) {
                dateList41.add(format);
            }
        }

        for (Timestamp t : dateList5) {
            String format = df.format(new Date(t.getTime()));
            if (!dateList51.contains(format)) {
                dateList51.add(format);
            }
        }


        DeviceInfoPO device = null;
        // 再根据时间，药水类型到数据库中获取数据
        for (LinePO line : lines) {

            List<DataVO> list1 = new ArrayList<>();
            List<DataVO> list2 = new ArrayList<>();
            List<DataVO> list3 = new ArrayList<>();
            List<DataVO> list4 = new ArrayList<>();
            List<DataVO> list5 = new ArrayList<>();


            tableName = concatTableName(line.getId());

            device = new DeviceInfoPO();
            device.setLineId(line.getId());

            for (String date : dateList11) {
                DataVO dataVO = dataRecMapper.liquidMedicine(tableName, 8, "\'" + date + "\'");
                if (dataVO == null) {
                    dataVO = new DataVO();
                    dataVO.setValue(new BigDecimal(0));
                    dataVO.setTime(date);
                    device.setDevType(8);
                    setUpperLimitAndLowerLimit(device, dataVO);
                }
                list1.add(dataVO);
            }

            for (String date : dateList21) {
                DataVO dataVO = dataRecMapper.liquidMedicine(tableName, 9, "\'" + date + "\'");
                if (dataVO == null) {
                    dataVO = new DataVO();
                    dataVO.setValue(new BigDecimal(0));
                    dataVO.setTime(date);
                    device.setDevType(9);
                    setUpperLimitAndLowerLimit(device, dataVO);
                }
                list2.add(dataVO);
            }

            for (String date : dateList31) {
                DataVO dataVO = dataRecMapper.liquidMedicine(tableName, 11, "\'" + date + "\'");
                if (dataVO == null) {
                    dataVO = new DataVO();
                    dataVO.setValue(new BigDecimal(0));
                    dataVO.setTime(date);
                    device.setDevType(11);
                    setUpperLimitAndLowerLimit(device, dataVO);
                }
                list3.add(dataVO);
            }

            for (String date : dateList41) {
                DataVO dataVO = dataRecMapper.liquidMedicine(tableName, 12, "\'" + date + "\'");
                if (dataVO == null) {
                    dataVO = new DataVO();
                    dataVO.setValue(new BigDecimal(0));
                    dataVO.setTime(date);
                    device.setDevType(12);
                    setUpperLimitAndLowerLimit(device, dataVO);
                }
                list4.add(dataVO);
            }

            for (String date : dateList51) {
                DataVO dataVO = dataRecMapper.liquidMedicine(tableName, 10, "\'" + date + "\'");
                if (dataVO == null) {
                    dataVO = new DataVO();
                    dataVO.setValue(new BigDecimal(0));
                    dataVO.setTime(date);
                    device.setDevType(10);
                    setUpperLimitAndLowerLimit(device, dataVO);
                }
                list5.add(dataVO);
            }

            datas1.put(line.getName(), list1);
            datas2.put(line.getName(), list2);
            datas3.put(line.getName(), list3);
            datas4.put(line.getName(), list4);
            datas5.put(line.getName(), list5);
        }

        // 8.碳酸钠 9.氢氧化钠 11.氯酸钠12盐酸
        result.put("碳酸钠浓度", datas1);
        result.put("氢氧化钠浓度", datas2);
        result.put("氯酸钠浓度", datas3);
        result.put("盐酸浓度", datas4);
        result.put("比重", datas5);

        return result;

    }

    private void setUpperLimitAndLowerLimit(DeviceInfoPO device, DataVO dataVO) {
        List<DeviceInfoPO> deviceInfos = deviceInfoMapper.queryDeviceInfo(device);
        if (!CollectionUtils.isEmpty(deviceInfos)) {
            device = deviceInfos.get(0);
            dataVO.setLowerLimit(device.getLowerLimit());
            dataVO.setUpperLimit(device.getUpperLimit());
        }
    }

    private String concatTableName(Integer lineId) {
        // 计算当前季度
        int quarter = (Calendar.getInstance().get(Calendar.MONTH) + 1 + 2) / 3;
        int year = Calendar.getInstance().get(Calendar.YEAR);
        return "data_rec_" + lineId + "_" + year + "_q" + quarter;
    }

    private List<String> concatTableName(Integer lineId, Timestamp start, Timestamp end) {
        // // 计算当前季度
        // int quarter = (Calendar.getInstance().get(Calendar.MONTH) + 1 + 2) / 3;
        // int year = Calendar.getInstance().get(Calendar.YEAR);

        Calendar startInstance = Calendar.getInstance();
        startInstance.setTimeInMillis(start.getTime());

        int quarterStart = (startInstance.get(Calendar.MONTH) + 1 + 2) / 3;
        int yearStart = startInstance.get(Calendar.YEAR);


        Calendar endInstance = Calendar.getInstance();
        endInstance.setTimeInMillis(end.getTime());

        int quarterEnd = (endInstance.get(Calendar.MONTH) + 1 + 2) / 3;
        int yearEnd = endInstance.get(Calendar.YEAR);

        List<String> tableNames = new ArrayList<>();

        if (yearStart == yearEnd) {
            for (int i = quarterStart; i <= quarterEnd; i++) {
                tableNames.add("data_rec_" + lineId + "_" + yearStart + "_q" + i);
            }
        } else if (yearStart < yearEnd) {
            for (int i = quarterStart; i <= 4; i++) {
                tableNames.add("data_rec_" + lineId + "_" + yearStart + "_q" + i);
            }
            for (int i = (yearStart + 1); i <= yearEnd; i++) {
                if (i == yearEnd) {
                    for (int j = 1; j <= quarterEnd; j++) {
                        tableNames.add("data_rec_" + lineId + "_" + i + "_q" + j);
                    }
                } else {
                    for (int j = 1; j <= 4; j++) {
                        tableNames.add("data_rec_" + lineId + "_" + i + "_q" + j);
                    }
                }
            }
        }


        // return "data_rec_" + lineId + "_" + year + "_q" + quarter;
        return tableNames;
    }

}
